#!/usr/bin/env python
# -*- coding: utf-8 -*-
#  comment.py
#  description

#  Created by zhouzongli633 on 2020/8/17 9:22 上午.
#  Copyright ©Intellectus All rights reserved.
import datetime
import json

from Common.decorators import method, check_body
from Common.logger import app_log
from Common.response import resp
# from Common.PushManager import PushManager
from User.models import Comments, Posts, Notifications
from Baby.models import UsersBabies, Users


def comments(params={}):
    comment_ret = []
    if 'post_id' in params and params['post_id']:
        comment_ret = comment_for_post(params['post_id'])
    elif 'feed_id' in params and params['feed_id']:
        comment_ret = comment_for_feed(params['feed_id'], params['user_id'])
    elif 'milestone_id' in params and params['milestone_id']:
        comment_ret = comment_for_milestone(params['milestone_id', params['user_id']])

    return comment_ret


def comment_for_post(post_id):
    p_record = Posts.objects.get(id=post_id)
    c_records = p_record.comments.all()
    comments_ret = []
    for it in c_records:
        comments_ret.append(it.comments_include_user_to_json())
    return comments_ret


def comment_for_feed(feed_id, user_id):
    ret = []
    all_babies = UsersBabies.objects.filter(users_id=user_id).all().values('baby_id')
    all_users = UsersBabies.objects.filter(baby_id__in=all_babies).all().values('users_id')
    records = Comments.objects.filter(feed_id=feed_id, user_id__in=all_users).all()
    for it in records:
        it_json = it.comments_include_user_to_json()
        ret.append(it_json)
    return ret


def comment_for_milestone(milestone_id, user_id):
    ret = []
    all_babies = UsersBabies.objects.filter(users_id=user_id).all().values('baby_id')
    all_users = UsersBabies.objects.filter(baby_id__in=all_babies).all().values('users_id')
    records = Comments.objects.filter(milestone_id=milestone_id, user_id__in=all_users).all()
    for it in records:
        it_json = it.comments_include_user_to_json()
        ret.append(it_json)
    return ret


@method(['POST'])
@check_body(['user_id', 'comment_text'])
def create(request):
    try:
        params = json.loads(request.body)
        user = Users.objects.filter(id=params['user_id']).first()
        if not user:
            return resp(4001)

        if (('post_id' in params and params['post_id']) and
                ('feed_id' in params and params['feed_id']) and
                ('milestone_id' in params and params['milestone_id'])):
            return resp(-1, 'Params missing')
        post = None
        if 'post_id' in params and params['post_id']:
            post = Posts.objects.filter(id=params['post_id']).first()
            if not post:
                return resp(4001)
            if post.user != user:
                message = f"{user.full_name} commented :{params['comment_text']}"
                notif = Notifications(
                    user=post.user,
                    post=post,
                    type='comment',
                    notifier=user.id,
                    message=message
                )
                notif.save()
                # PushManager().push_message_with_user(post.user, message)

        parent = None
        if 'parent' in params:
            parent = params['parent']
            parent_comment = Comments.objects.filter(id=parent).first()
            if user != parent_comment.user:
                message = f"{user.full_name} mentioned you in a comment:#{parent_comment.user.full_name}# {params['comment_text']}"
                notif = Notifications(
                    user=parent_comment.user,
                    post=post,
                    type='mention',
                    notifier=user.id,
                    message=message
                )
                notif.save()
                # PushManager().push_message_with_user(post.user, message)
        record = Comments(
            user=user,
            comment_text=params['comment_text'],
            post=post,
            feed_id=params['feed_id'] if 'feed_id' in params else None,
            milestone_id=params['milestone_id'] if 'milestone_id' in params else None,
            parent=parent if parent else None
        )
        record.save()

        ret = post.posts_include_media_to_json()
        return resp(0, ret)

    except Exception as e:
        app_log.exception(e)
        return resp(-1, str(e))


@method(['GET'])
def show(request):
    try:
        user_id = request.GET.get('user_id')
        feed_id = request.GET.get('feed_id')
        post_id = request.GET.get('post_id')
        milestone_id = request.GET.get('milestone_id')
        if not user_id:
            return resp(4001)
        if not feed_id and not post_id and not milestone_id:
            return resp(4001)

        ret = comments(params=request.GET)
        return resp(0, ret)
    except Exception as e:
        app_log.exception(e)
        return resp(-1, str(e))
